import sys
import time
from PyQt6.QtWidgets import QApplication, QProgressDialog, QMainWindow, QVBoxLayout, QWidget, QPushButton


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Loading Example")
        self.setGeometry(100, 100, 400, 200)

        # 创建中心 widget 和布局
        central_widget = QWidget()
        layout = QVBoxLayout()
        central_widget.setLayout(layout)
        self.setCentralWidget(central_widget)

        # 创建 "开始加载" 按钮
        self.start_button = QPushButton("Start Loading")
        self.start_button.clicked.connect(self.start_loading)
        layout.addWidget(self.start_button)

    def start_loading(self):
        """模拟加载过程"""
        # 创建 QProgressDialog
        progress_dialog = QProgressDialog("Loading...", "Cancel", 0, 100, self)
        progress_dialog.setWindowTitle("Loading")
        progress_dialog.setModal(True)
        progress_dialog.show()

        # 模拟加载过程
        for i in range(101):
            progress_dialog.setValue(i)
            time.sleep(0.1)
            if progress_dialog.wasCanceled():
                break

        progress_dialog.close()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec())